//
//  QTTFirstPageViewController.m
//  QuTouTiao
//
//  Created by 杨杨子 on 2018/6/18.
//  Copyright © 2018年 杨杨子. All rights reserved.
//

#import "QTTFirstPageViewController.h"
#import "QTTThreePicCell.h"
#import "QTTDislikeView.h"
#import "QTTVideoCell.h"
#import "QTTAdCell.h"
#import "QTTLastTimeHereCell.h"
#import "QTTRightImageCell.h"
#import "QTTZXYDSearchView.h"
#import "QTTAddItemScrollView.h"
#import "QTTPublicBtn.h"
#import "XLChannelControl.h"

@interface QTTFirstPageViewController ()<UITableViewDelegate,UITableViewDataSource>
//@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) QTTDislikeView *disLikeView;
@property (nonatomic,strong) UIView *grayAlphaView;
@property (nonatomic,strong) QTTZXYDSearchView *searchView;
@property (nonatomic,strong) UIView *topHeadView;
@property (nonatomic,strong) NSMutableArray *itemArray;
@property (nonatomic,strong) UIScrollView *baseScrollView;
@property (nonatomic,strong) QTTPublicBtn *addBtn;
@property (nonatomic,assign) NSInteger selectCount;
@property (nonatomic,strong) QTTAddItemScrollView *itemScrollView;
@property (nonatomic,strong) NSMutableArray *unUseItemArray;
@property (nonatomic,strong) NSMutableArray *itemBtnArray;
@property (nonatomic,strong) QTTPublicBtn *selectButton;
@end

@implementation QTTFirstPageViewController
-(NSMutableArray *)itemArray{
    if (!_itemArray) {//@[@"推荐",@"时尚",@"广州",@"热点",@"娱乐",@"健康",@"养生"]
        _itemArray = [NSMutableArray arrayWithArray:@[@"推荐",@"时尚",@"广州"]];
        NSLog(@"_itemArray_itemArray:%@",_itemArray);
    }
    return _itemArray;
}
-(NSMutableArray *)unUseItemArray{
    if (!_unUseItemArray) {
        _unUseItemArray = [NSMutableArray arrayWithArray:@[@"有声",@"家居",@"电竞",@"美容",@"电视剧",@"搏击",@"健康",@"摄影",@"生活",@"旅游",@"韩流",@"探索",@"综艺",@"美食",@"育儿"]];
    }
    return _unUseItemArray;
}
-(NSMutableArray *)itemBtnArray{
    if (!_itemBtnArray) {
        _itemBtnArray = [NSMutableArray array];
    }
    return _itemBtnArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.selectCount = 0;
    [self createView];
    self.grayAlphaView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:self.grayAlphaView];
    self.grayAlphaView.backgroundColor = [UIColor grayColor];
    self.grayAlphaView.alpha = 0;
 
}

-(void)createView{
     [self createTopHeadView];
     [self createBaseScrollView];
    
}
-(void)createTopHeadView{
    
    //
    self.topHeadView = [[UIView alloc] initWithFrame:CGRectMake(0, [UIApplication sharedApplication].statusBarFrame.size.height, SCREEN_WIDTH, 90)];
    [self.view addSubview:self.topHeadView];
    self.topHeadView.backgroundColor = [UIColor lightGrayColor];
    //
    self.searchView = [[QTTZXYDSearchView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    [self.topHeadView addSubview:self.searchView];
    self.searchView.backgroundColor = [UIColor clearColor];
    self.searchView.searchTextField.backgroundColor = [UIColor whiteColor];
    self.searchView.searchTextField.placeholder = @" 搜索内容";
    self.searchView.block = ^(NSString *searchStr){
        
    };
    //
    CGFloat itemViewHeight = 40;
    QTTAddItemScrollView *itemScrollView = [[QTTAddItemScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchView.frame), SCREEN_WIDTH-itemViewHeight, itemViewHeight) AndArray:self.itemArray];
    self.itemScrollView = itemScrollView;
    for (NSInteger index = 0; index < self.itemScrollView.subviews.count; index ++) {
        QTTPublicBtn *btn = self.itemScrollView.subviews[index];
        [self.itemBtnArray addObject:btn];
    }
    self.selectButton = self.itemBtnArray[0];//默认是推荐
    self.itemScrollView.showsVerticalScrollIndicator = NO;
    self.itemScrollView.showsHorizontalScrollIndicator = NO;
//    以下前两行与第三行任意混搭都能实现按钮点击及scrollview的拖拽
    [self.itemScrollView setDelaysContentTouches:NO];//默认值为YES；如果设置为NO，则无论手指移动的多么快，始终都会将触摸事件传递给内部控件；设置为NO可能会影响到UIScrollView的滚动功能。
    [self.itemScrollView setCanCancelContentTouches:YES];//如果属性值为YES并且跟踪到手指正触摸到一个内容控件，这时如果用户拖动手指的距离足够产生滚动，那么内容控件将收到一个touchesCancelled:withEvent:消息，而scroll view将这次触摸作为滚动来处理。如果值为NO，一旦content view开始跟踪(tracking==YES)，则无论手指是否移动，scrollView都不会滚动。
     self.itemScrollView.panGestureRecognizer.delaysTouchesBegan = YES;

    [self.topHeadView addSubview:itemScrollView];
    itemScrollView.scrollEnabled = YES;
    itemScrollView.userInteractionEnabled = YES;
    CGFloat width = 60;
    itemScrollView.contentSize = CGSizeMake(self.itemArray.count * width, itemScrollView.height);
    itemScrollView.actionBringSthBlock = ^(NSString *senderTagStr){
        
    };
    //
    QTTPublicBtn *addBtn = [[QTTPublicBtn alloc] initWithFrame:CGRectMake(CGRectGetMaxX(itemScrollView.frame), CGRectGetMaxY(self.searchView.frame), itemViewHeight, itemViewHeight)];
    self.addBtn = addBtn;
    [self.topHeadView addSubview:addBtn];
    [addBtn setBackgroundImage:[UIImage imageNamed:@"u12"] forState:UIControlStateNormal];
    [self.addBtn addTarget:self action:@selector(addBtn:) forControlEvents:UIControlEventTouchUpInside];
    
}
-(void)addItemButton{//加按钮
    QTTPublicBtn *button = [[QTTPublicBtn alloc] initWithFrame:CGRectMake(60 * (self.itemArray.count-1), 0, 60, self.itemScrollView.height) andTittle:[self.itemArray lastObject] AndTittleColor:[UIColor blackColor] AndTittleFont:16 AndBackColor:[UIColor clearColor] AndFatherView:self.itemScrollView];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    button.tag = self.itemArray.count - 1;
    self.itemScrollView.contentSize = CGSizeMake(60 * self.itemArray.count, self.itemScrollView.height);
    [self.itemBtnArray addObject:button];
}
-(void)createTableViewWithFrame:(CGRect)frame
{
    UITableView *tableView = [[UITableView alloc] initWithFrame:frame];
    [self.baseScrollView addSubview:tableView];
    self.baseScrollView.contentSize = CGSizeMake(SCREEN_WIDTH * self.itemArray.count, self.baseScrollView.height);
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.estimatedRowHeight = 80;
    
    [tableView registerNib:[UINib nibWithNibName:@"QTTThreePicCell" bundle:nil] forCellReuseIdentifier:@"QTTThreePicCell"];
    [tableView registerNib:[UINib nibWithNibName:@"QTTVideoCell" bundle:nil] forCellReuseIdentifier:@"QTTVideoCell"];
    [tableView registerNib:[UINib nibWithNibName:@"QTTAdCell" bundle:nil] forCellReuseIdentifier:@"QTTAdCell"];
    [tableView registerNib:[UINib nibWithNibName:@"QTTLastTimeHereCell" bundle:nil] forCellReuseIdentifier:@"QTTLastTimeHereCell"];
    [tableView registerNib:[UINib nibWithNibName:@"QTTRightImageCell" bundle:nil] forCellReuseIdentifier:@"QTTRightImageCell"];
    
}

-(void)createBaseScrollView{
    self.baseScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.topHeadView.frame), SCREEN_WIDTH, SCREEN_HEIGHT - CGRectGetMaxY(self.topHeadView.frame))];
    [self.view addSubview:self.baseScrollView];
    self.baseScrollView.pagingEnabled = YES;
    self.baseScrollView.showsHorizontalScrollIndicator = NO;
    self.baseScrollView.showsVerticalScrollIndicator = NO;
    self.baseScrollView.contentSize = CGSizeMake(SCREEN_WIDTH * self.itemArray.count, self.baseScrollView.height);
    self.baseScrollView.contentSize = CGSizeMake(SCREEN_WIDTH * self.itemArray.count, self.baseScrollView.height);
    //
    for (NSInteger index = 0; index < self.itemArray.count; index ++) {
        [self createTableViewWithFrame:CGRectMake(index * SCREEN_WIDTH, 0, SCREEN_WIDTH, self.baseScrollView.height)];
    }
    
}
#pragma -mark- action
-(void)addBtn:(UIButton *)sender
{
    __weak typeof (self) weakSelf = self;
    
    [[XLChannelControl shareControl] showChannelViewWithInUseTitles:self.itemArray unUseTitles:self.unUseItemArray finish:^(NSArray *inUseTitles, NSArray *unUseTitles) {
        NSString *lastItem = [NSString stringWithUTF8String:[[inUseTitles lastObject] UTF8String]];
        if (![[weakSelf.itemArray lastObject] isEqualToString:lastItem]) {//新添加了频道
             [weakSelf.itemArray addObject:lastItem];
        }else{//没添加频道（选了新的以前添加的频道/没选新的频道/删除了当前选中的频道，默认是推荐）
            
        }
        
        NSLog(@"itemArrayitemArray:%@",weakSelf.itemArray);
        [weakSelf addItemButton];
        [weakSelf createTableViewWithFrame:CGRectMake((weakSelf.itemArray.count - 1) * SCREEN_WIDTH, 0, SCREEN_WIDTH, weakSelf.baseScrollView.height)];
    }];
}
//{//假数据
//    [self.itemArray addObject:@"时尚"];
//    {//加按钮
//        QTTPublicBtn *button = [[QTTPublicBtn alloc] initWithFrame:CGRectMake(60 * (self.itemArray.count-1), 0, 60, self.itemScrollView.height) andTittle:[self.itemArray lastObject] AndTittleColor:[UIColor blackColor] AndTittleFont:16 AndBackColor:[UIColor clearColor] AndFatherView:self.itemScrollView];
//        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
//        button.tag = self.itemArray.count - 1;
//        self.itemScrollView.contentSize = CGSizeMake(60 * self.itemArray.count, self.itemScrollView.height);
//    }
//    [self createTableViewWithFrame:CGRectMake((self.itemArray.count - 1) * SCREEN_WIDTH, 0, SCREEN_WIDTH, self.baseScrollView.height)];
//
//}
-(void)buttonAction:(UIButton *)sender{
    if (self.itemScrollView.actionBringSthBlock) {
        self.itemScrollView.actionBringSthBlock([NSString stringWithFormat:@"%lu",sender.tag]);
    }
}
#pragma -mark- UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        QTTThreePicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QTTThreePicCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        typeof (self) weakSelf = self;
        typeof (cell) weakCell = cell;
        NSLog(@"xBTNxBTNxBTN:%f",cell.xBTN.x);
        
        cell.xBtnClock = ^(){
            CGFloat space = 10;
            if (weakSelf.disLikeView) {
                [weakSelf.disLikeView removeFromSuperview];
            }
            weakSelf.disLikeView = [[[NSBundle mainBundle] loadNibNamed:@"QTTDislikeView" owner:self options:nil] firstObject];
            NSLog(@"xBTNy:%f SCREEN_HEIGHT:%f",CGRectGetMaxY(weakCell.frame),SCREEN_HEIGHT);
            CGFloat y = CGRectGetMaxY(weakCell.frame) - tableView.contentOffset.y;
            CGFloat disLikeViewHeight = 170;
            
            if (y + disLikeViewHeight > SCREEN_HEIGHT) {
                weakSelf.disLikeView.frame = CGRectMake(space * 3, y-disLikeViewHeight, SCREEN_WIDTH - space * 4, disLikeViewHeight);
            }else{
                weakSelf.disLikeView.frame = CGRectMake(space * 3, y-10, SCREEN_WIDTH - space * 4, disLikeViewHeight);
            }
            [weakSelf.view addSubview:weakSelf.disLikeView];
            weakSelf.grayAlphaView.alpha = 0.4;
        };
        return cell;
    }else if(indexPath.row == 1){
        QTTVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QTTVideoCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        typeof (self) weakSelf = self;
        typeof (cell) weakCell = cell;
        NSLog(@"xBTNxBTNxBTN:%f",cell.xBTN.x);
        
        cell.xBtnClock = ^(){
            CGFloat space = 10;
            if (weakSelf.disLikeView) {
                [weakSelf.disLikeView removeFromSuperview];
            }
            weakSelf.disLikeView = [[[NSBundle mainBundle] loadNibNamed:@"QTTDislikeView" owner:self options:nil] firstObject];
            NSLog(@"xBTNy:%f SCREEN_HEIGHT:%f",CGRectGetMaxY(weakCell.frame),SCREEN_HEIGHT);
            CGFloat y = CGRectGetMaxY(weakCell.frame) - tableView.contentOffset.y;
            CGFloat disLikeViewHeight = 170;
            
            if (y + disLikeViewHeight > SCREEN_HEIGHT) {
                weakSelf.disLikeView.frame = CGRectMake(space * 3, y-disLikeViewHeight, SCREEN_WIDTH - space * 4, disLikeViewHeight);
            }else{
                weakSelf.disLikeView.frame = CGRectMake(space * 3, y-10, SCREEN_WIDTH - space * 4, disLikeViewHeight);
            }
            [weakSelf.view addSubview:weakSelf.disLikeView];
            weakSelf.grayAlphaView.alpha = 0.4;
        };
        return cell;
    }else if(indexPath.row == 2){
        QTTAdCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QTTAdCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
       
        return cell;
    }else if(indexPath.row == 3){
        QTTLastTimeHereCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QTTLastTimeHereCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }else{
        QTTRightImageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QTTRightImageCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
  
    return UITableViewAutomaticDimension;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
#pragma -mark- usedManyTimes
-(void)removeDislikeViewAndAlphaView{
    self.grayAlphaView.alpha = 0.0;
    if (self.disLikeView) {
        [self.disLikeView removeFromSuperview];
    }
}
#pragma -mark- action

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self removeDislikeViewAndAlphaView];
}

@end
